package com.tensai.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.tensai.core.mvc.base.tools.ResultJson;
import com.tensai.core.mvc.base.tools.SessionInfo;
import com.tensai.core.constant.HttpProtocol;
import com.tensai.core.constant.ResponseStatus;
import com.tensai.core.constant.ServletPathNoSessionAccess;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * session拦截器
 *
 * @author kissy
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        for (ServletPathNoSessionAccess servletPath : ServletPathNoSessionAccess.values()) {
            if (request.getServletPath().contains(servletPath.getValue())) {
                return true;
            }
        }
        SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
        if (!ObjectUtils.allNotNull(sessionInfo)) {
            printJson(response);
            return false;
        }
        return true;
    }

    /**
     * afterCompletion在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面），
     * 可以根据ex是否为null判断是否发生了异常，进行日志记录；
     *
     * @param request   请求
     * @param response  响应
     * @param handler   句柄
     * @param ex        异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.setHeader(HttpProtocol.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        response.setHeader(HttpProtocol.ACCESS_CONTROL_ALLOW_HEADERS, "Authorization, Content-Type, X-Requested-With, token");
        response.setHeader(HttpProtocol.ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, OPTIONS, POST, PUT, DELETE");
        response.setHeader(HttpProtocol.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.setHeader(HttpProtocol.ACCESS_CONTROL_MAX_AGE, "3600");
//        vary: Origin
//        Vary: Access-Control-Request-Method
//        Vary: Access-Control-Request-Headers
//        Access-Control-Allow-Origin: *
    }

    private static void printJson(HttpServletResponse response) {
        ResultJson resultJson = new ResultJson(ResponseStatus.LOGIN_TIMOUT);
        resultJson.setCode(1001);
        String content = JSON.toJSONString(resultJson);
        printContent(response, content);
    }


    private static void printContent(HttpServletResponse response, String content) {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
